package com.xiaobias;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class BuTask implements Runnable {

    private ByteBuffer buffer;

    private final SocketChannel socketChannel;

    public BuTask(ByteBuffer readBuffer, SocketChannel socketChannel) {
        this.buffer = readBuffer;
        this.socketChannel = socketChannel;
    }

    @Override
    public void run() {
        try {
            // 处理数据 做业务
            buffer.flip();
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            buffer = null;
            // decode
            String msg = new String(bytes, Charset.defaultCharset());
            System.out.println("服务端接收到客户端的数据：" + msg);
            // 业务处理......

            // 向客户端写数据
            byte[] bytes1 = "hello, reactor client \n".getBytes(StandardCharsets.UTF_8);
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes1.length);
            writeBuffer.put(bytes1);
            writeBuffer.flip();
            socketChannel.write(writeBuffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
